<?php

namespace app\unify\middleware;

use app\unify\model\Config;
use app\unify\model\ConfigGroup;
use think\Request;

class LoadUnifyConfig
{
    public function handle(Request $r, \Closure $next)
    {
        $configGroupList = ConfigGroup::field('id,name')->select()->toArray();
        $configGroupList = array_column($configGroupList, 'name', 'id');

        $valuesList = [];

        Config::where([
            'status' => Config::STATUS_ENABLE,
        ])->field('group_id,name,value')->select()->each(function ($item) use ($configGroupList, &$valuesList) {
            if (!isset($configGroupList[$item['groupId']])) {
                return;
            }

            $groupName = $configGroupList[$item['groupId']];

            if (!isset($valuesList[$groupName])) {
                $valuesList[$groupName] = [];
            }

            $valuesList[$groupName][$item['name']] = $item['value'];

        });

        foreach ($valuesList as $group => $values) {
            \think\facade\Config::set($values, $group);
        }
        app()->debug(config('sys.app_debug') == 1);

        return $next($r);
    }

}